package com.gem.talkbase.fragment;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import com.gem.talkbase.R;
import com.gem.talkbase.activity.ChangePassActivity;
import com.gem.talkbase.activity.ChatMessageService;
import com.gem.talkbase.activity.FeedBackActivity;
import com.gem.talkbase.activity.Fragment_find_AddFriend;
import com.gem.talkbase.activity.LocationPeople;
import com.gem.talkbase.activity.LoginActivity;
import com.gem.talkbase.activity.Setinformation_aboutus;
import com.gem.talkbase.activity.Setinformation_mydata;
import com.gem.talkbase.activity.Setinformation_setting_fuzhu;
import com.gem.talkbase.activity.Setinformation_setting_message;
import com.gem.talkbase.bean.Firend;
import com.gem.talkbase.client.Client;
import com.gem.talkbase.service.JSON_Friend_info;
import com.gem.talkbase.service.JSON_GetFirend_Unick;
import com.gem.talkbase.util.DialogUtil;
import com.gem.talkbase.util.Setinformation_tools;
import com.gem.talkbase.util.Split_String;
import com.gem.talkbase.util.StreamTools;
import com.gem.talkbase.util.XmppTool;
import com.gem.talkbase.widget.TitleView;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;


/*
 * 功能描述：设置fragment页面
 * 
 * 
 */
public class Fragment_Settings extends Fragment implements OnClickListener{




	/*------------------------------------头像--------------------------------------*/	
	/*组件*/
	private RelativeLayout switchAvatar;
	String requestPath=Client.Login_image;
	List<Firend> list;
	private ImageView faceImage;
	String imageString;
	private String[] items = new String[] { "选择本地图片", "拍照" };
	/*头像名称*/
	private  String IMAGE_FILE_NAME = Environment.getExternalStorageDirectory().getPath()+"/faceimage.png";

	/* 请求码*/
	private static final int IMAGE_REQUEST_CODE = 0;
	private static final int CAMERA_REQUEST_CODE = 1;
	private static final int RESULT_REQUEST_CODE = 2;
	/*------------------------------------头像--------------------------------------*/ 
	/*------------------------------------上传图片--------------------------------------*/
	private String newName;
	private String uploadFile;
	private String actionUrl =Client.actionUrl;
	private String who = null;
	private String WHO_PIC = Client.WHO_PIC;
	/*------------------------------------上传图片--------------------------------------*/




	private View mParent;
	private View mExitMenuView;
	private FragmentActivity mActivity;
	private Button mExitBtn;
	private TitleView mTitle;
	private View mFeedBackView;
	private View mchangePass,mdataView;
	private  TextView tv_unick,tv_ipone;
	private ImageView iv_face;
	private Button mExitCancleBtn;
	private Button mExitConfirmBtn;
	FinalBitmap fb ;
	
	String nicheng,sex,mysay,user_unick;
	SharedPreferences sharedPreferences,sharedPreferences1,sharedPreferences2; //获得登录者的id
	private static final String URL = Client.FRAGMENT_SETTINGS_URL;
	private Handler handler = new Handler(){

		@Override

		public void handleMessage(Message msg) {

			switch(msg.what){

			case 1:   //吧消息传到我的资料页面
				Bundle data = msg.getData();  
				String result1 = data.getString("result");
				System.out.println(result1+"======================================result1");

				if (result1.length()==0) {
					nicheng = "新用户";
					sex = "男";
					mysay = " ";
				}else {
					String[] tt = result1.split( Split_String.split_s1);
					nicheng = tt[0];
					sex = tt[1];
					mysay = tt[2];
				}




				//处理UI更新等操作  
				Intent intent = new Intent(getActivity(),Setinformation_mydata.class);
				intent.putExtra("image", imageString);
				intent.putExtra("nicheng",nicheng);
				intent.putExtra("sex",sex);
				intent.putExtra("mysay",mysay);
				getActivity().startActivity(intent);
				//		break ;
			case 2:
				//Toast.makeText(getActivity(), "服务器正在维护！",Toast.LENGTH_SHORT).show();

				break ;  
			case 3:   //上传图片成功与否的提示

				Bundle data3 = msg.getData();  
				String result = data3.getString("COUNT");
				Toast.makeText(getActivity(), result,Toast.LENGTH_SHORT).show();
				break ;
			case 4:
				Toast.makeText(getActivity(), "图片更新成功",Toast.LENGTH_LONG).show();
				break;
			case 5:
				Toast.makeText(getActivity(), "图片更新失败",Toast.LENGTH_LONG).show();
				break;

			}

		}



	};

	/*----------------------------------------my do------------------------------------------*/

	private View set_message,set_fuzhu,set_about,set_share;

	/*----------------------------------------my do------------------------------------------*/	



	/**
	 * Create a new instance of DetailsFragment, initialized to show the text at
	 * 'index'.
	 */
	public static Fragment_find newInstance(int index) {
		Fragment_find f = new Fragment_find();

		// Supply index input as an argument.
		Bundle args = new Bundle();
		args.putInt("index", index);
		f.setArguments(args);

		return f;
	}

	public int getShownIndex() {
		return getArguments().getInt("index", 0);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater
				.inflate(R.layout.fragment_settings, container, false);


		sharedPreferences =getActivity().getSharedPreferences(Client.SAVE_USER,getActivity().MODE_PRIVATE);//获得登录者的信息
		sharedPreferences1 =getActivity().getSharedPreferences(Client.RGISTER_STRING,getActivity().MODE_PRIVATE);//获得登录者的信息
		sharedPreferences2 =getActivity().getSharedPreferences(Client.RGISTER_UNICK,getActivity().MODE_PRIVATE);//获得登录者的信息
		//获得登录者的信息
		String userid = sharedPreferences.getString("userid", ""); 
		if (userid.length()==0) {
			userid = sharedPreferences1.getString("user_id", ""); 
			who=userid;
		}else {
			who = userid;
		}

		Bundle bundle= this.getArguments();
		if(bundle!=null){
		user_unick=bundle.getString("unick");//得到登录id号

		}
		newName = who+".png";
		System.out.println("==========================================================="+newName);
		uploadFile =Environment.getExternalStorageDirectory().getPath()+"/"+who+".png";
		System.out.println("==========================================================="+uploadFile);
		/*------------------------------------头像--------------------------------------*/	
		switchAvatar = (RelativeLayout) view.findViewById(R.id.frameLayout1);
		faceImage = (ImageView) view.findViewById(R.id.face);
		//设置事件监听
		switchAvatar.setOnClickListener(listener);
		/*------------------------------------头像--------------------------------------*/


		mExitMenuView = LayoutInflater.from(getActivity()).inflate(
				R.layout.common_menu_dialog_2btn_layout, null);
		mExitBtn = (Button) view.findViewById(R.id.exit_app);
		mExitBtn.setOnClickListener(this);
		mExitCancleBtn = (Button) mExitMenuView.findViewById(R.id.btnCancel);
		mExitConfirmBtn = (Button) mExitMenuView
				.findViewById(R.id.btn_exit_comfirm);
		mExitConfirmBtn.setText(R.string.exit);
		mExitCancleBtn.setOnClickListener(this);
		mExitConfirmBtn.setOnClickListener(this);
		//==========给“意见反馈”布局设置监听器===========================
		mFeedBackView = view.findViewById(R.id.set_feedback);
		mFeedBackView.setOnClickListener(this);
		mchangePass=view.findViewById(R.id.changePass1);
		mchangePass.setOnClickListener(this);
		//==========个人资料======================================		
		mdataView=view.findViewById(R.id.accountSetting1);
		mdataView.setOnClickListener(this);

		/*----------------------------my do------------------------*/
//		set_message=view.findViewById(R.id.set_message);
//		set_message.setOnClickListener(this);
//
//		set_fuzhu=view.findViewById(R.id.set_fuzhu);
//		set_fuzhu.setOnClickListener(this);

		
		set_share=view.findViewById(R.id.displaySetting4);
		set_share.setOnClickListener(this);
		
		
		set_about=view.findViewById(R.id.set_about);
		set_about.setOnClickListener(this);

		/*----------------------------my do------------------------*/

		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		fb = FinalBitmap.create(getActivity());
		mParent = getView();
		mActivity = getActivity();
		sharedPreferences =getActivity().getSharedPreferences(Client.SAVE_USER,getActivity().MODE_PRIVATE);//获得登录者的信息
		String userid = sharedPreferences.getString("userid", ""); 
		String unick = sharedPreferences.getString("username", ""); 
		String userimage = sharedPreferences.getString("userimage", ""); 
		System.out.println("userid===="+userid);
		System.out.println("unick===="+unick);
		System.out.println("userimage===="+userimage);
		mTitle = (TitleView) mParent.findViewById(R.id.title);
		mTitle.setTitle(R.string.title_settings_1);

		iv_face=(ImageView)mParent.findViewById(R.id.face);
		fb.display(iv_face,userimage);
		tv_ipone=(TextView)mParent.findViewById(R.id.ipone2);
		tv_ipone.setText(userid);
		tv_unick=(TextView)mParent.findViewById(R.id.status);
		String unickString=sharedPreferences2.getString("user_unick", "");
		Bundle bundle= this.getArguments();
		if(bundle!=null){
		user_unick=bundle.getString("unick");//得到登录id号
		System.out.println(user_unick+"=================user_unick======================");
		}
		if(userid.length()==0){
			System.out.println("=asdjasjkdfasdkjgfgfsdakjf============================");
			userid = sharedPreferences1.getString("user_id", ""); //注册id
			System.out.println(userid+"=======================userid1");
			if (unickString.length()!=0) {
				tv_unick.setText(unickString);
				tv_ipone.setText(userid);
			}else {
				tv_ipone.setText(userid);
				tv_unick.setText("编辑资料");
			}

		}else {
			if (user_unick!=null) {
				tv_unick.setText(user_unick); 
				System.out.println(nicheng+"=======================nicheng");
				System.out.println(user_unick+"=================user_unick1");
			}else {
				tv_ipone.setText(userid);
				if (user_unick!=null) {   
					System.out.println(user_unick+"=================user_unick2");
					tv_unick.setText(user_unick);	    
				}else {
					System.out.println(user_unick+"=================user_unick3");
					tv_unick.setText(unick);
				}			
			}		
		}	
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}
	private Dialog mExitDialog;
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.accountSetting1:

			final String userid = sharedPreferences.getString("userid", ""); 




			new Thread(new Runnable() { 

				@Override

				public void run() {

					try {

						HttpClient client = new DefaultHttpClient();
						//提交数据的路径
						HttpPost httpPost =new HttpPost(URL);
						//指定要提交数据的实体
						List<NameValuePair> parameters = new ArrayList<NameValuePair>();
						if (userid.length()==0) {
							final String userid1=sharedPreferences.getString("user_id", ""); 
							System.out.println("我学会编程========================");
							parameters.add( new BasicNameValuePair("zhangsan", userid1));
						}else {
							parameters.add( new BasicNameValuePair("zhangsan", userid));
						}
						parameters.add( new BasicNameValuePair("act", "act_main"));

						httpPost.setEntity(new UrlEncodedFormEntity(parameters,"utf-8"));
						//敲回车
						HttpResponse response = client.execute(httpPost);
						int code = response.getStatusLine().getStatusCode();
						System.out.println("response.getStatusLine().getStatusCode()==="+response.getStatusLine().getStatusCode());
						if (code == 200) {


							InputStream is = response.getEntity().getContent();
							String result = StreamTools.readInputStream(is);
							//System.out.println("result..<><><><><>..."+result);

							Message msg = new Message() ;

							//这三句可以传递数据  
							Bundle data = new Bundle();  
							data.putString("result", result);//result是标签,handleMessage中使用  
							msg.setData(data); 

							msg.what = 1 ;

							Fragment_Settings.this.handler.sendMessage(msg);

						}  else{

							Message msg = new Message() ;						
							msg.what = 2 ;
							Fragment_Settings.this.handler.sendMessage(msg);
						}

					} catch (UnsupportedEncodingException e) {

						e.printStackTrace();

					} catch (ClientProtocolException e) {

						e.printStackTrace();

					} catch (IOException e) {

						e.printStackTrace();

					}

				}

			}).start();	

			break;	
		case R.id.set_feedback:
			startActivity(new Intent(getActivity(), FeedBackActivity.class));
			break;
		case R.id.changePass1:
			startActivity(new Intent(getActivity(), ChangePassActivity.class));
			break;
		case R.id.exit_app:
			if (mExitDialog == null)
				mExitDialog = DialogUtil.getMenuDialog(getActivity(),
						mExitMenuView);
			mExitDialog.show();
			break;

			//==============点击退出按钮里面的注销。
		case R.id.btnCancel:
			if (mExitDialog != null && mExitDialog.isShowing())
				mExitDialog.dismiss();
			Intent intent =new Intent(getActivity(),LoginActivity.class);
			startActivity(intent);
			clear();
			XmppTool.closeConnection();

			System.exit(0);
			//   getActivity().finish();
			break;
			//=============点击退出按钮里面的退出。
		case R.id.btn_exit_comfirm:

			//		XXService service = mFragmentCallBack.getService();
			//			if (service != null) {
			//				service.logout();// 注销
			//				service.stopSelf();// 停止服务
			//			}
			//			if(mExitDialog.isShowing()){  
			//				mExitDialog.cancel();
			//			}
			clear();
			XmppTool.closeConnection();
			System.exit(0);
			//android.os.Process.killProcess(android.os.Process.myPid());

			break;
			/*----------------------my do----------------------*/

//		case R.id.set_message:
//
//			startActivity(new Intent(getActivity(), Setinformation_setting_message.class));
//			break;
//
//		case R.id.set_fuzhu:
//
//			startActivity(new Intent(getActivity(), Setinformation_setting_fuzhu.class));
//			break;
			
		case R.id.displaySetting4:
			
			//分享哦那个图片，首先把它存在本地，然后从本地读取。
			InputStream is = getResources().openRawResource(R.drawable.icon);    
			Bitmap mBitmap = BitmapFactory.decodeStream(is);
			File f = new File(Environment.getExternalStorageDirectory().getPath()+"/talkbaseImage.png");//把图片保存到本地

			try {
				f.createNewFile();

				FileOutputStream fOut = null;

				fOut = new FileOutputStream(f);

				mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);

				fOut.flush();

				fOut.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			
			
			
			
			String str = "你还在用QQ吗？你还在用微信吗？那你太out了，现在大家都在用talkbase，" +
				    "talkbase拥有强大的聊天功能，有你意想不到的有趣栏目。快快来下载吧。下载地址:" +
				    "http://apk.hiapk.com/  "+
				    "  ps:应用还未上市，敬请期待。";
		
		
		shareMsg(getActivity(),"talkbase","talkbase",str,Environment.getExternalStorageDirectory().getPath()+"/talkbaseImage.png");
			break;

		case R.id.set_about:

			startActivity(new Intent(getActivity(), Setinformation_aboutus.class));
			break;

			/*----------------------my do----------------------*/
		}
	}
	//==================清空登录的sharedpreferences================
	public void clear(){
		Editor editor = sharedPreferences.edit();  
		Editor editor1 = sharedPreferences1.edit();  
		Editor editor2= sharedPreferences2.edit();  


		editor.clear().commit();   
		editor1.clear().commit();   
		editor2.clear().commit();   

	}



	/*------------------------------------头像--------------------------------------*/
	private View.OnClickListener listener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {//头像的监听事件，点击后有效。
			showDialog();
		}
	};
	/**
	 * 显示选择对话框
	 */
	private void showDialog() {

		new AlertDialog.Builder(getActivity())
		.setTitle("设置头像")
		.setItems(items, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case 0:

					Intent intentFromGallery = new Intent();
					intentFromGallery.setType("image/*"); // 设置文件类型
					intentFromGallery
					.setAction(Intent.ACTION_GET_CONTENT);
					startActivityForResult(intentFromGallery,
							IMAGE_REQUEST_CODE);

					//finish();
					break;
				case 1:

					Intent intentFromCapture = new Intent(
							MediaStore.ACTION_IMAGE_CAPTURE);
					// 判断存储卡是否可以用，可用进行存储
					if (Setinformation_tools.hasSdcard()) {

						intentFromCapture.putExtra(
								MediaStore.EXTRA_OUTPUT,
								Uri.fromFile(new File(IMAGE_FILE_NAME)));
					}

					startActivityForResult(intentFromCapture,
							CAMERA_REQUEST_CODE);
					//finish();
					break;
				}
			}
		})
		.setNegativeButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		}).show();

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {


		if (resultCode != 0) {//必须要判断，不然在图库中返回时会报错，若返回的部位零，则进入下一步，否则返回到我的资料页面

			switch (requestCode) {
			case IMAGE_REQUEST_CODE:

				startPhotoZoom(data.getData());

				break;
			case CAMERA_REQUEST_CODE:
				if (Setinformation_tools.hasSdcard()) {
					File tempFile = new File(IMAGE_FILE_NAME);
					startPhotoZoom(Uri.fromFile(tempFile));
				} else {
					Toast.makeText(getActivity(), "未找到存储卡，无法存储照片！",
							Toast.LENGTH_LONG).show();
				}

				break;
			case RESULT_REQUEST_CODE:
				if (data != null) {
					getImageToView(data);
					putpic();
				}
				break;
			}
		}else{
			return ;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 裁剪图片方法实现
	 * 
	 * @param uri
	 */
	public void startPhotoZoom(Uri uri) {

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 设置裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 320);
		intent.putExtra("outputY", 320);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, RESULT_REQUEST_CODE);
	}

	/**
	 * 保存裁剪之后的图片数据
	 * 
	 * @param picdata
	 * @return 
	 * @throws IOException 
	 */
	private void getImageToView(Intent data) {
		Bundle extras = data.getExtras();

		if (extras != null) {

			Bitmap photo = extras.getParcelable("data");
			Drawable drawable = new BitmapDrawable(photo);
			faceImage.setImageDrawable(drawable);
			clearhuancun();
			File f = new File(Environment.getExternalStorageDirectory().getPath()+"/"+who+".png");//把图片保存到本地

			try {
				f.createNewFile();

				FileOutputStream fOut = null;

				fOut = new FileOutputStream(f);

				photo.compress(Bitmap.CompressFormat.PNG, 100, fOut);

				fOut.flush();

				fOut.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}
	/*------------------------------------头像--------------------------------------*/		

	/*------------------------------------上传图片到服务器的封装类--------------------------------------*/
	private void uploadFile()
	{
		String end ="\r\n";
		String twoHyphens ="--";
		String boundary ="*****";
		try
		{
			java.net.URL url =new java.net.URL(actionUrl);
			HttpURLConnection con=(HttpURLConnection)url.openConnection();
			//允许Input、Output，不使用Cache 
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false);
			//设置传送的method=POST 
			con.setRequestMethod("POST");
			//setRequestProperty 
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", "UTF-8");
			con.setRequestProperty("Content-Type",
					"multipart/form-data;boundary="+boundary);
			//设置DataOutputStream 
			DataOutputStream ds =
					new DataOutputStream(con.getOutputStream());
			ds.writeBytes(twoHyphens + boundary + end);
			ds.writeBytes("Content-Disposition: form-data; "+
					"name=\"file1\";filename=\""+
					newName +"\""+ end);
			ds.writeBytes(end);  
			// 取得文件的FileInputStream 
			FileInputStream fStream =new FileInputStream(uploadFile);
			//设置每次写入1024bytes 
			int bufferSize =1024;
			byte[] buffer =new byte[bufferSize];
			int length =-1;
			//从文件读取数据至缓冲区 
			while((length = fStream.read(buffer)) !=-1)
			{
				//将资料写入DataOutputStream中 
				ds.write(buffer, 0, length);
			}
			ds.writeBytes(end);
			ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
			// close streams 
			fStream.close();
			ds.flush();
			//取得Response内容 
			InputStream is = con.getInputStream();
			int ch;
			StringBuffer b =new StringBuffer();
			while( ( ch = is.read() ) !=-1 )
			{
				b.append( (char)ch );
			}
			//将Response显示于Dialog 
			//showDialog("上传成功"+b.toString().trim());


			Message msg = new Message() ;


			Bundle data = new Bundle();  
			data.putString("COUNT", "上传成功"+b.toString().trim());//COUNT是标签,handleMessage中使用  
			msg.setData(data);  


			msg.what = 3 ;

			Fragment_Settings.this.handler.sendMessage(msg);



			//关闭DataOutputStream 
			ds.close();
		}
		catch(Exception e)
		{
			//showDialog("上传失败"+e);


			Message msg = new Message() ;


			Bundle data = new Bundle();  
			data.putString("COUNT", "上传失败"+e+"请选择一张有效的图片");//COUNT是标签,handleMessage中使用  
			msg.setData(data);  


			msg.what = 2 ;

			Fragment_Settings.this.handler.sendMessage(msg);
		}

	}
	/*------------------------------------去除空格，回车，换行--------------------------------------*/	
	public static String replaceBlank(String str) {  
		String dest = "";  
		if (str!=null) {  
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");  
			Matcher m = p.matcher(str);  
			dest = m.replaceAll("");  
		}  
		return dest;  
	}



	public void putpic(){		
		/*------------------------------------子线程提交数据-------------------------------------*/
		uploadFile();//上传图片
		new Thread(new Runnable() {
			public void run(){
				try {

					HttpClient client = new DefaultHttpClient();
					//提交数据的路径
					HttpPost httpPost =new HttpPost(WHO_PIC);
					httpPost.addHeader("charset", HTTP.UTF_8);				
					//指定要提交数据的实体
					List<NameValuePair> parameters = new ArrayList<NameValuePair>();
					parameters.add( new BasicNameValuePair("username", who));//把图片的名字加后缀名传到服务器
					httpPost.setEntity(new UrlEncodedFormEntity(parameters,"utf-8"));
					//敲回车
					HttpResponse response = client.execute(httpPost);
					int code = response.getStatusLine().getStatusCode();//获得返回码，为200是则表示提交且返回成功
					if (code == 200) {
						InputStream is = response.getEntity().getContent();
						String result = StreamTools.readInputStream(is); //获取从服务器拿到的数据
						Message msg = new Message() ;
						if(result!=null){ //如果拿到的为真，则打印一个toase
							if(result.equals("true")){
								msg.what = 4 ;
								Fragment_Settings.this.handler.sendMessage(msg);
							}else{
								msg.what = 5 ;
								Fragment_Settings.this.handler.sendMessage(msg);
							}
						}else{
							msg.what = 5 ;
							Fragment_Settings.this.handler.sendMessage(msg);
						}

					}  

				} catch (UnsupportedEncodingException e) {

					e.printStackTrace();

				} catch (ClientProtocolException e) {

					e.printStackTrace();

				} catch (IOException e) {

					e.printStackTrace();

				}

			}


		}).start();

	}






	public void clearhuancun(){


		if(ExistSDCard()){
			System.out.println("======================shanchu wenjian=================");
			 File file = new File(Environment.getExternalStorageDirectory().getPath()
					        +"/Android/data/com.gem.talkbase/cache");
			 file.delete();
		
		}
	}
	
	
	
		private boolean ExistSDCard() {  
			if (android.os.Environment.getExternalStorageState().equals(  
					android.os.Environment.MEDIA_MOUNTED)) {  
				return true;  
			} else  
				return false;  
		} 


		
		
		
		
		
		/**   
		  * 分享功能   
		  * @param context 上下文   
		  * @param activityTitle Activity的名字   
		  * @param msgTitle 消息标题   
		  * @param msgText 消息内容   
		  * @param imgPath 图片路径，不分享图片则传null   
		  */    
		 public static void shareMsg(Context context, String activityTitle, String msgTitle, String msgText,    
		   String imgPath) {    
		  Intent intent = new Intent(Intent.ACTION_SEND);   
		  
		  if (imgPath == null || imgPath.equals("")) {    
		   intent.setType("text/plain"); // 纯文本    
		  } else {    
		   File f = new File(imgPath);    
		   if (f != null && f.exists() && f.isFile()) {    
		    intent.setType("image/png");    
		    Uri u = Uri.fromFile(f);    
		    intent.putExtra(Intent.EXTRA_STREAM, u);    
		   }    
		  }    
		  intent.putExtra(Intent.EXTRA_SUBJECT, msgTitle);    
		  intent.putExtra(Intent.EXTRA_TEXT, msgText);    
		  intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);    
		  context.startActivity(Intent.createChooser(intent, activityTitle));    
		 } 

		
		
		
		


	}
